<template>
  <!--回到顶部-->
  <transition
    enter-active-class="w-animated w-bounceInRight"
    leave-active-class="w-animated w-bounceOutRight">
    <div
      v-if="backTop > 100"
      class="back-top w-round w-flex-center"
      @click="backTopClick">
      <i class="el-icon-arrow-up"/>
    </div>
  </transition>
</template>

<script lang="ts">
import { ScrollTop } from 'yb-tool'
import { Component, Vue } from 'vue-property-decorator'

@Component({
})

export default class BackTop extends Vue {
  // 是否显示返回顶部
  private backTop = 0
  // 定时器
  private timer = null

  private mounted() {
    window.addEventListener('scroll', this.handleScroll, false);
    window.addEventListener('resize', this.handleScroll, false);
  }

  private beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll, false);
    window.removeEventListener('resize', this.handleScroll, false);
  }

  // 返回到顶部
  private backTopClick() {
    const sTop = this.scrollTop()
    ScrollTop(window, sTop, 0, 800);
  }

  // 监听网站滚动，显示向上箭头
  private handleScroll() {
    this.backTop = this.scrollTop();
  }

  // 获取顶部
  private scrollTop() {
    let sTop = 0
    if (document.documentElement) {
      sTop = document.documentElement.scrollTop
    } else {
      sTop = document.body.scrollTop
    }
    return sTop
  }
}

</script>

<style scoped>
  .back-top {
    position: fixed;
    right: 30px;
    bottom: 30px;
    width: 40px;
    height: 40px;
    background-color: rgba(0, 0, 0, .5);
    color: #eee;
    font-size: 24px;
  }
</style>
